package com.server.auth.service.impl;

import com.server.auth.service.AuthService;
import com.server.liad.api.user.remote.RemoteUserService;
import com.server.common.code.utils.ResultUtil;
import com.server.model.all.user.bo.LoginBo;
import com.server.model.all.user.bo.SmsLoginBo;
import com.server.common.code.utils.Result;
import com.server.model.all.enums.sms.SmsTypeEnum;
import com.server.common.code.vo.LoginVo;
import com.server.common.code.utils.OptionalUtils;
import com.server.common.redis.service.RedisSmsService;
import com.server.common.redis.token.TokenServices;
import com.server.common.redis.service.verify.RedisLoginVerifyService;
import com.server.common.redis.vo.TokenVo;
import com.server.common.security.code.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Resource
    private TokenServices tokenServices;


    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private RedisLoginVerifyService redisLoginVerifyService;

    @Resource
    private RedisSmsService redisSmsService;

    @Override
    public TokenVo login(LoginBo loginBo) {
        String ipAddress = SecurityUtils.getIpAddress();

        tokenServices.checkLoginFailNumMore(ipAddress);

        Result<LoginVo> loginVoResult = remoteUserService.login(loginBo);
        //登录失败写入redis +1
        OptionalUtils.ofEmpty(loginVoResult.getData())
                .ifNotPresent(() -> {
                    tokenServices.loginFailNumIncrement(ipAddress);
                });
        //再抛出异常
        LoginVo loginVo = ResultUtil.getDataThrowException(loginVoResult);

        TokenVo tokenVo = tokenServices.createToken(loginVo);

        tokenServices.loginFailNumDel(ipAddress);

        redisLoginVerifyService.delLoginVerify(loginBo.getTextCode());

        return tokenVo;
    }

    @Override
    public TokenVo smsLogin(SmsLoginBo smsLoginBo) {
        String ipAddress = SecurityUtils.getIpAddress();

        tokenServices.checkLoginFailNumMore(ipAddress);

        Result<LoginVo> loginVoResult = remoteUserService.smsLogin(smsLoginBo);
        //登录失败写入redis +1
        OptionalUtils.ofEmpty(loginVoResult.getData())
                .ifNotPresent(() -> {
                    tokenServices.loginFailNumIncrement(ipAddress);
                });
        //再抛出异常
        LoginVo loginVo = ResultUtil.getDataThrowException(loginVoResult);

        TokenVo tokenVo = tokenServices.createToken(loginVo);

        tokenServices.loginFailNumDel(ipAddress);

        redisSmsService.delSmsCode(SmsTypeEnum.LOGIN.getSmsTypeRedisKey(), smsLoginBo.getMobile());

        return tokenVo;
    }
}
